package io_nio;

import java.nio.ByteBuffer;

public class BufferDemo {
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(8);
        System.out.println("capacity is "+buffer.capacity());
        System.out.println("limit is "+buffer.limit() );
        System.out.println("position is "+buffer.position());
        System.out.println("====================");
        buffer.put("a".getBytes());
        buffer.put("b".getBytes());
        buffer.put("c".getBytes());
        System.out.println("position is "+buffer.position());
        buffer.flip();//把limit移动到position，把position指针归0，准备写入数据。即每次读取数据都是从0开始，读到limit的位置就结束
        System.out.println("limit is "+buffer.limit());
        System.out.println("position is "+buffer.position());
        System.out.println("==================");
        byte b = buffer.get();//取出第一个元素,同时position指针向后移动一位
        System.out.println("取出第一个元素是："+b);
        System.out.println("position is "+buffer.position());
        System.out.println("=================");
        buffer.clear();//limit移动到capacity,position移动到0，而缓冲区中的数据不会被清空
        System.out.println("position is "+buffer.position());
        System.out.println("limit is "+buffer.limit());
        System.out.println("第一个元素是"+buffer.get(0));//根据索引取值时，不会影响position的位置
    }
}
